<?php
/**
 * Created by PhpStorm.
 * User: zengyuming
 * Date: 2017/7/15
 * Time: 上午10:21
 */
namespace Api\Controller;
use Think\Controller;
class CommonController extends Controller {
    //判断是否为微信浏览器
    protected function isWx(){
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            // 非微信浏览器禁止浏览
            return false;
        } else {
            // 获取版本号
            preg_match('/.*?(MicroMessenger\/([0-9.]+))\s*/', $user_agent, $matches);
            return $matches[2];
        }
    }

    # 验证商户
    protected function CheckBaseparam($data){
        $checkres = D('Merchant')->datacheck();
        if($checkres != '0'){ // 基础参数验证
            echo json_encode(array('error' => 1 , 'msg' => $checkres . '参数不合法'),JSON_UNESCAPED_UNICODE);
            exit;
        }
        $mchidcheck = D('merchant')->where(array('merchant_id' => $data['partner']))->count();
        if($mchidcheck <= 0){
//            echo json_encode(array('error' => 7 , 'msg' => $data['partner'] . '商户号不存在'),JSON_UNESCAPED_UNICODE);
            echo json_encode(array('error' => 7 , 'msg' => '参数不合法mch'),JSON_UNESCAPED_UNICODE);
            exit;
        }
        $merchantData = M('merchant')
            ->alias('a')
            ->join('left join zym_user as b on a.userid = b.id')
            -> where(array('a.merchant_id' => $data['partner']))
            ->find();


        $iSignData = array(
            'partner' => $data['partner'],
            'banktype' => $data['banktype'],
            'ordernumber' => $data['ordernumber'],
            'paymoney' => $data['paymoney'],
            "order_time" => $data['order_time'],
//            'notify_url' => urldecode($data['notify_url']),
            'notify_url' => str_replace('&amp;','&',urldecode($data['notify_url'])),
            'ClientIp' => $data['ClientIp'],
        ); // 加入签名的参数

        if($data['banktype'] == 'bank_pay' || $data['banktype'] == 'weixin_pay' && $data['user_id'] != '') $iSignData['user_id'] = $data['user_id'];
        $MySign = SetMySign($iSignData,$merchantData['merchant_key']);


        if($data['sign'] !== $MySign){
            \Think\Log::write('SignError-' . json_encode($data), 'WARN', '', LOG_PATH . "Api/CreateOrder/" . $data['banktype'] . '/' . date('Y-m-d') . ".log");
            exit(json_encode(array('error' => 2 , 'msg' => 'sign参数不合法'),JSON_UNESCAPED_UNICODE));
        }

        if($merchantData['userstatus'] == '1'){
            exit(json_encode(array('error' => 3 , 'msg' =>  '接口未开启'),JSON_UNESCAPED_UNICODE));
        }

        // 也可以用过order_time 参数来验证订单时间

        $data['href_backurl'] = isset($data['href_backurl']) ? strip_tags($data['href_backurl']) : ''; // 支付成功跳转的地址 可空 不加入签名
        $count = M('Transaction')->where(array('out_trade_no' => $data['ordernumber']))->count();
        if($count > 0){
            exit(json_encode(array('error' => 4 , 'msg' =>  '该订单已存在'),JSON_UNESCAPED_UNICODE));
        }

        return $merchantData;
    }

    /* 返回引导页面的url地址 自动判断微信浏览器 */
    protected function alipaydisplayUrl($url,$order_number , $is_alipay = false){
        $Sign = strtoupper(md5($url . $order_number .  C("SignKey")));
        if(!$is_alipay) {
            $AlipayPayurl = 'http://' . $_SERVER['HTTP_HOST'] . '/Api/AlipayPay/ocdiaoqizhifuSM?payurl=' . base64_encode($url) . '&order=' . base64_encode($order_number) . '&Sign=' . $Sign; // 跳转到不需要登录的页面支付
        }else{
            $AlipayPayurl = 'http://' . $_SERVER['HTTP_HOST'] . '/Api/AlipayPay/ocdiaoqizhifuSM?payurl=' . base64_encode($url) . '&order=' . base64_encode($order_number) . '&Sign=' . $Sign . "&is_alipay=true"; // 跳转到不需要登录的页面支付
        }
        return $AlipayPayurl;
    }



    /* 公共调起h5支付 */
    // 参数1 掉起支付的payInfo信息
    protected function transferH5Pay($payInfo , $return_url , $channel){
        /*
         * 充值域名H5公共掉起
         *  www.gongzhiwei.cn
            www.guajindeng.cn
            www.guangdianmo.cn
         *
         * */
        $Sra_code = base64_encode(json_encode($payInfo));
        $payType = 'ChangbaoGzh';
        $NowTime = time();
        $signche = md5($Sra_code . $return_url . $payType . $NowTime . "d709285ea607325e69207c6c3b87e1a2");
//        $iurl = 'http://www.jxwtrl.cn/Home/Index/'. $channel .'/Gzhpayment.php?wxpayConfig=' . $Sra_code . '&payType=' . $payType . '&time=' . $NowTime . '&AfterpayUrl=' . $return_url . '&sign=' . $signche; // 统一调起H5公众号支付
        $iurl = 'http://www.gongzhiwei.cn/'. $channel .'/Gzhpayment.php?wxpayConfig=' . $Sra_code . '&payType=' . $payType . '&time=' . $NowTime . '&AfterpayUrl=' . $return_url . '&sign=' . $signche; // 统一调起H5公众号支付
        header("Location:" . $iurl);
    }


    /* 此静态方法为CreateController减少代码冗余 */
    protected static function getparameter($transactionData){
        // 订单创建成功，开始进入支付模式
        $get_data = array(
            'banktype' => $transactionData['pay_type'],
            'paymoney' => $transactionData['paymoney'],
            'ordernumber' => $transactionData['out_trade_no'],
            'systrade_no' => $transactionData['systrade_no'],
            'return_url' => $transactionData['callback_url']
        );
        return $get_data;
    }
}